package com.cmcc.aregister.cs.lazyimage;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.util.MyLogger;
import com.cmcc.aregister.cs.util.Utils;

public class LazyImageView extends ImageView {
	private static final String TAG = "LazyImageView";
	private String mLocal;
	private String mRemote;
	private HTTPThread mThread = null;
	private int mType;
	private int retryTime;
	private Context context;

	private int[] defaultImageId = { R.drawable.hospital_image_default,
			R.drawable.doctor_image_default };

	private MyLogger logger = MyLogger.getLogger();

	public LazyImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public LazyImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
	}

	public void loadImage(String urlstr, int type, int defaultType) {
		if (urlstr == null || "".equals(urlstr)) {
			setImageResource(defaultImageId[defaultType]);
			return;
		}
		setTag(urlstr);
		retryTime = 0;
		mType = type;
		mRemote = urlstr;
		String temp = Utils.changePicUrl(urlstr);
		temp = GlobalSetting.CACHE_PIC_PATH + temp;
		if(ConfigUtilHelper.debug){
			Log.i(TAG,"urlstr:" + urlstr + "-temp-" + temp);
		}
		mLocal = temp;

		Bitmap bit = BitmapFactory.decodeFile(temp, Utils.getOptions(temp));
		// Bitmap bit = BitmapFactory.decodeFile(temp, Utils.getOptions(temp));
		if (bit != null) {
			if (getTag().hashCode() == mRemote.hashCode()) {
				BitmapDrawable bd = new BitmapDrawable(bit);
				setBackgroundDrawable(bd);
			} else {
				logger.d("-----------tag false");
			}
		} else {
			setBackgroundResource(defaultImageId[defaultType]);
			queue();
		}
	}
	
	public void loadImageUnCut(String urlstr, int type, int defaultType){
	    if (urlstr == null || "".equals(urlstr)) {
            setImageResource(defaultImageId[defaultType]);
            return;
        }
        setTag(urlstr);
        retryTime = 0;
        mType = type;
        mRemote = urlstr;
        String temp =urlstr; //Utils.changePicUrl(urlstr);
        temp = GlobalSetting.CACHE_PIC_PATH + temp;
        if(ConfigUtilHelper.debug){
            Log.i(TAG,"urlstr:" + urlstr + "-temp-" + temp);
        }
        mLocal = temp;

        Bitmap bit = BitmapFactory.decodeFile(temp);
        // Bitmap bit = BitmapFactory.decodeFile(temp, Utils.getOptions(temp));
        if (bit != null) {
            if (getTag().hashCode() == mRemote.hashCode()) {
                BitmapDrawable bd = new BitmapDrawable(bit);
                setBackgroundDrawable(bd);
            } else {
                logger.d("-----------tag false");
            }
        } else {
            setBackgroundResource(defaultImageId[defaultType]);
            queue();
        }
	}

	@Override
	public void finalize() {
		if (mThread != null) {
			HTTPQueue queue = HTTPQueue.getInstance();
			queue.dequeue(mThread);
		}
	}

	private void queue() {
		if (mThread != null) {
			HTTPQueue queue = HTTPQueue.getInstance();
			queue.dequeue(mThread);
		}
		logger.d("=====LazyImageView==Remote=" + mRemote);
		mThread = new HTTPThread(mRemote, mLocal, mType, mHandler);
		HTTPQueue queue = HTTPQueue.getInstance();
		queue.enqueue(mThread, HTTPQueue.PRIORITY_LOW);
	}

	private void queueLow() {
		if (mThread == null) {
			mThread = new HTTPThread(mRemote, mLocal, mType, mHandler);
			HTTPQueue queue = HTTPQueue.getInstance();
			queue.enqueue(mThread);
		}
	}

	private void setFromLocal(Bitmap bit, int hashCode) {
		if (bit != null) {
			if (hashCode == mRemote.hashCode()) {
				logger.d("-----------setFromLocal");
				BitmapDrawable bd = new BitmapDrawable(bit);
				setBackgroundDrawable(bd);
			} else {
				logger.d("-----------tag false");
			}
		} else {
			logger.d("-----------bit null");
			if (retryTime < 1) {
				retryTime++;
				queueLow();
			}
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bitmap bit = (Bitmap) msg.obj;
			int hashCode = msg.arg1;
			setFromLocal(bit, hashCode);
		}
	};
}
